package com.cloud2eye.auth.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenAuth implements Serializable {
    static final String CLAIM_KEY_USERNAME = "sub";
    static final String CLAIM_KEY_IP = "IP";
    static final String CLAIM_KEY_USERID = "userId";
    static final String CLAIM_KEY_EMPID = "empId";
    static final String CLAIM_KEY_EMPNAME = "empName";
    static final String CLAIM_KEY_AUTHORITY = "authority";
    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    @Value("${jwt.header}")
    private String tokenHeader;

    public String getUsernameFromToken(String token) {
        String username;
        try {
            final Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    public Date getExpirationDateFromToken(String token) {
        Date expiration;
        try {
            final Claims claims = getClaimsFromToken(token);
            expiration = claims.getExpiration();
        } catch (Exception e) {
            expiration = null;
        }
        return expiration;
    }

    public String getIPfromToken(String token){
        String ip;
        try {
            final Claims claims = getClaimsFromToken(token);
            ip = (String) claims.get(CLAIM_KEY_IP);
        } catch (Exception e) {
            ip = null;
        }
        return ip;
    }

    private Claims getClaimsFromToken(String token) {
//        Claims claims;
        Claims claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        return claims;
    }

    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    private Boolean isTheSameip(String token, String ip){
        final String tip = getIPfromToken(token);
        return ip.equalsIgnoreCase(tip);
    }

    public String generateToken(UserDetails userDetails, String ip) {
        JwtUser user = (JwtUser) userDetails;
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_IP, ip);
        claims.put(CLAIM_KEY_USERID,user.getId());
        claims.put(CLAIM_KEY_EMPID,user.getEmpId());
        claims.put(CLAIM_KEY_EMPNAME,user.getEmpName());
        //claims.put(CLAIM_KEY_AUTHORITY,user.getAuthorities());
        return generateToken(claims);
    }

    String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Boolean validateToken(String token, String ip, UserDetails userDetails) {
        JwtUser user = (JwtUser) userDetails;
        final String username = getUsernameFromToken(token);
        return (
                username.equals(user.getUsername())
                        && isTheSameip(token, ip)
                        && !isTokenExpired(token)
                );
    }
    public String getUserNameFromRequest(HttpServletRequest request){
        String authToken = request.getHeader(this.tokenHeader);
        String username = this.getUsernameFromToken(authToken);
        return username;
    }

}